package com.gipson.amc.service.basicdata;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsbj.common.msg.ResponseMessage;
import com.gipson.amc.entity.*;
import com.gipson.amc.mapper.UserRoleMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 用户角色 服务实现类
 * </p>
 *
 * @author xsyuan
 * @since 2020-03-27
 */
@Service
public class UserRoleService extends ServiceImpl<UserRoleMapper, UserRole> {

    public IPage<UserRole> selectPageForUserRole(UserRole userRole , PageByDataTable pageByDataTable){
        Page<UserRole> page=new Page<UserRole>().setSize(pageByDataTable.getPagesize()).setCurrent(pageByDataTable.getPageindex());
        return baseMapper.queryPageData(page,userRole,pageByDataTable);
    }

    @Transactional
    public ResponseMessage deleteUserRole(String userId,String roleId) {
        Map<Object,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("roleId",roleId);
        baseMapper.deleteUserRole(map);
        return ResponseMessage.ok("删除成功！");
    }

    @Transactional
    public ResponseMessage saveUserRole(String id,String userIds){
        if(StringUtils.isNotBlank(userIds)){
            List<String> userIdsList = new ArrayList<>();
            String[] arr = StringUtils.split(userIds,",");
            for (int i = 0; i < arr.length; i++) {
                //根据userid  roleid对比查询
                Map<Object,Object> map = new HashMap<>();
                map.put("userId",arr[i]);
                map.put("roleId",id);
                UserRole userRole = baseMapper.findByMap(map);
                if(null == userRole){
                    userIdsList.add(arr[i]);
                }
            }

            if(CollectionUtils.isNotEmpty(userIdsList)){
                for (int i = 0; i < userIdsList.size(); i++) {
                    UserRole userRole = new UserRole();
                    userRole.setRoleId(id);
                    userRole.setUserId(userIdsList.get(i));
                    save(userRole);
                }
            }
        }
        return ResponseMessage.ok("添加用户成功！");
    }


}
